package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.ICategoryService;
import com.mmall.service.IProductService;
import com.mmall.util.DateTimeUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import com.mmall.vo.ProductListVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author:lzq
 * @date: 2018/3/20 12:31
 */
@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService iCategoryService;

    public ServerResponse saveProduct(Product product){
        //图片的第一张作为主图
        if(StringUtils.isNotEmpty(product.getSubImages())){
            String[] imgs = product.getSubImages().split(",");
            if(imgs.length>0){
                product.setMainImage(imgs[0]);
            }
        }
        if(product.getId() != null){
            int count = productMapper.updateByPrimaryKey(product);
            if(count>0){
                return ServerResponse.createBySuccessMessage("商品更新成功");
            }else {
                return ServerResponse.createBySuccessMessage("商品更新失败");
            }
        }else {
            int count = productMapper.insertSelective(product);
            if(count>0){
                return ServerResponse.createBySuccessMessage("商品添加成功");
            }else{
                return ServerResponse.createBySuccessMessage("商品添加失败");
            }
        }
    }

    public ServerResponse setStaus(Integer productId,Integer status){
        if(productId==null||status==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        product.setStatus(status);
        int count = productMapper.updateByPrimaryKeySelective(product);
        if(count>0){
            return ServerResponse.createBySuccessMessage("产品状态更新成功");
        }
        return ServerResponse.createByErrorMessage("产品状态更新失败，请检查参数是否正确");
    }

    //后台管理员获取商品详情
    public ServerResponse<ProductDetailVo> getDetail(Integer productId){
        if(productId==null){
            return  ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"获取商品详情时参数异常");
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if(product==null){
            return ServerResponse.createByErrorMessage("商品已下架！");
        }
        return ServerResponse.createBySuccess(assembleProductDetail(product));
    }

    private ProductDetailVo assembleProductDetail(Product product){
        ProductDetailVo detailVo=new ProductDetailVo();
        detailVo.setId(product.getId());
        detailVo.setSubtitle(product.getSubtitle());
        detailVo.setPrice(product.getPrice());
        detailVo.setMainImage(product.getMainImage());
        detailVo.setSubImages(product.getSubImages());
        detailVo.setCategoryId(product.getCategoryId());
        detailVo.setDetail(product.getDetail());
        detailVo.setName(product.getName());
        detailVo.setStatus(product.getStatus());
        detailVo.setStock(product.getStock());
        detailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        //这里要判断根节点是非为0
        if(category.getId()==null){
            detailVo.setCategoryId(0);
        }else{
            detailVo.setCategoryId(category.getId());
        }
        detailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        detailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
        return detailVo;
    }

    public ServerResponse getList(int pageSize,int pageNum){
        //pageHelper >start
        PageHelper.startPage(pageNum,pageSize);
        //执行要查询的sql
        List<Product> productList = productMapper.selectProductList();
        List<ProductListVo> productListVoList=new ArrayList<>();
        for (Product product : productList) {
            productListVoList.add(assembleProductListVo(product));
        }
        //pageinfo 收尾   插件会根据sql的返回结果自行封装到pageiInfo
        PageInfo pageInfo=new PageInfo(productList);
        //重新set想要返回给前端的结果
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(productListVoList);
    }

    private ProductListVo assembleProductListVo(Product product){
        ProductListVo productListVo = new ProductListVo();
        productListVo.setId(product.getId());
        productListVo.setName(product.getName());
        productListVo.setCategoryId(product.getCategoryId());
        productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
        productListVo.setMainImage(product.getMainImage());
        productListVo.setPrice(product.getPrice());
        productListVo.setSubtitle(product.getSubtitle());
        productListVo.setStatus(product.getStatus());
        return productListVo;
    }

    public ServerResponse search(int pageSize,int pageNum,String productName,Integer productId){
        PageHelper.startPage(pageNum, pageSize);
        if(StringUtils.isNotBlank(productName)){
            productName=new StringBuilder().append("%").append(productName).append("%").toString();
        }
        List<Product> productList = productMapper.selectProdecuByNameorId(productName, productId);
        List<ProductListVo> productListVoList=new ArrayList<>();
        for (Product product : productList) {
            productListVoList.add(assembleProductListVo(product));
        }
        PageInfo pageInfo=new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(productListVoList);
    }

    //前台用户获取商品详情
    public ServerResponse detail(Integer productId){
        if(productId!=null){
            Product product = productMapper.selectByPrimaryKey(productId);
            if(product==null){
                return ServerResponse.createByErrorMessage("产品已经下架或者删除");
            }
            if(product.getStatus()!= Const.ProductStatusEnum.ON_SALE.getCode()){
                return ServerResponse.createByErrorMessage("产品已经下架或者删除");
            }
            return ServerResponse.createBySuccess(assembleProductDetail(product));
        }
        return ServerResponse.createByErrorMessage("获取商品详情参数错误");
    }

   //前台的产品搜索及动态排序list
    public ServerResponse getProductByKeywordCategory(String keyword,Integer categoryId,Integer pageNum,Integer pageSize,String orderBy){
        if(StringUtils.isBlank(keyword) && categoryId==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"参数错误");
        }
        List<Integer> categoryidList=new ArrayList<>();
        if(categoryId!=null){
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if(category==null&&StringUtils.isBlank(keyword)){
                //此时返回一个空的结果集给前端即可
                PageHelper.startPage(pageNum,pageSize);
                List<ProductListVo> productvoList=new ArrayList<>();
                PageInfo pageInfo = new PageInfo(productvoList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            categoryidList = iCategoryService.selectCategoryAndChildrenById(category.getId()).getData();
        }
        //keyword拼接
        if(StringUtils.isNotBlank(keyword)){
            keyword=new StringBuilder().append("%").append(keyword).append("%").toString();
        }
        //排序处理
        if(StringUtils.isNotBlank(orderBy)&&Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
            String[] orderbyArray = orderBy.split("_");
            PageHelper.orderBy(orderbyArray[0]+orderbyArray[1]);
        }

        List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword)?null:keyword,categoryidList.size()==0?null:categoryidList);
        List<ProductListVo> productListVoList = Lists.newArrayList();
        for(Product product : productList){
            ProductListVo productListVo = assembleProductListVo(product);
            productListVoList.add(productListVo);
        }

        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }
}
